//
//  MTStepVC.m
//  met
//
//  Created by 李晓俊 on 2019/5/16.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "MTStepVC.h"
#import "MTTicketView.h"
#import <UShareUI/UShareUI.h>
#import "MTYaoQingView.h"
#import <CoreMotion/CoreMotion.h>
@interface MTStepVC ()<UMSocialShareMenuViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UILabel *chepiaoCount;

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) NSString *jumpUrl;

@property (weak, nonatomic) IBOutlet UIButton *kaiqiBut;
@property (weak, nonatomic) IBOutlet UIButton *rechargeBut;

@property (nonatomic,strong) CMPedometer *pedometer;
@end

@implementation MTStepVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"步数";
    self.tableView.backgroundColor = KBackColor;
    self.view.backgroundColor = KBackColor;
    
    UIView *foot = [UIView new];
    foot.backgroundColor = KBackColor;
    self.tableView.tableFooterView = foot;
    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.contentSize = CGSizeMake(26+138*3, 266);
    self.scrollView.frame = CGRectMake(0, 0, kScreenWidth, 266);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.bgView addSubview:self.scrollView];
    
    
    self.kaiqiBut.layer.borderWidth = 2;
    self.kaiqiBut.layer.borderColor = KMainBlueColor.CGColor;
    self.rechargeBut.layer.borderWidth = 2;
    self.rechargeBut.layer.borderColor = KMainBlueColor.CGColor;
    
    
    MTTicketView *first = [[MTTicketView alloc] initWithFrame:CGRectMake(26, 0, 128, 229)];
    first.numberimage.image = [UIImage imageNamed:@"车票1"];
    first.content.text =  @"邀请一位好友";
    first.tishi.text =  @"可获得10车票";
    first.count.text =  @"+10";
    [first.goBut setTitle:@"去邀请" forState:UIControlStateNormal];
    
    first.buttonClick = ^(NSString * s) {
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        AccountService *acc = [AccountService getObject];
        acc.httpRequestResultBlock = ^(id data,int code){
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (code == 1) {
                if ([[NSString stringWithFormat:@"%@",[data objectForKey:@"model"]]isEqualToString:@"1"]) {
                    
                }else {
                    //邀请链接
                    NSString *url = [NSString stringWithFormat:@"%@",[data objectForKey:@"content"]];
                    self.jumpUrl = url;
                    [self shareClick];
                }
            }else {
                [self.view maketishiToast:data];
            }
        };
        [acc findOthers:@"10"];
    };
    [self.scrollView addSubview:first];
    
    MTTicketView *second = [[MTTicketView alloc] initWithFrame:CGRectMake(26 + 138 *1, 0, 128, 229)];
    second.numberimage.image = [UIImage imageNamed:@"车票2"];
    second.content.text =  @"每日签到";
    second.tishi.text =  @"可获得5车票";
    second.count.text =  @"+5";
    [second.goBut setTitle:@"去签到" forState:UIControlStateNormal];
    second.buttonClick = ^(NSString * s) {
        if ([[NSString stringWithFormat:@"%@",KUSER.isSign]isEqualToString:@"1"]) {
            //已签到
            [[UIApplication sharedApplication].keyWindow maketishiToast:@"今日已签到"];
        }else {
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            AccountService *acc = [AccountService getObject];
            acc.httpRequestResultBlock = ^(id data,int code){
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (code == 1) {
                    [[UIApplication sharedApplication].keyWindow maketicket2Toast:@"5"];
                    [self getUserInfo];
                }else {
                    [self.view maketishiToast:data];
                }
            };
            [acc userSign];
        }
    };
    [self.scrollView addSubview:second];
    
    MTTicketView *third = [[MTTicketView alloc] initWithFrame:CGRectMake(26 + 138 *2 , 0, 128, 229)];
    third.numberimage.image = [UIImage imageNamed:@"车票3"];
    third.content.text =  @"步数兑换";
    third.tishi.text =  @"可获得10车票";
    third.count.text =  @"+10";
    [third.goBut setTitle:@"去记步" forState:UIControlStateNormal];
    [self.scrollView addSubview:third];

    [UMSocialUIManager setShareMenuViewDelegate:self];
    
    self.jumpUrl = @"";
    _pedometer = [[CMPedometer alloc] init];

}
- (UIView*)UMSocialParentView:(UIView*)defaultSuperView
{
    return [UIApplication sharedApplication].keyWindow;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [WRNavigationBar wr_setDefaultNavBarBarTintColor:KWhiteColor];
//    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:NO];
//    [self checkbushu];
     [self reloadData];
    if ([[NSString stringWithFormat:@"%@",KUSER.isReceive]isEqualToString:@"1"]) {
        self.rechargeBut.layer.borderWidth = 2;
        self.rechargeBut.layer.borderColor = HEXCOLOR(0xCCCCCC).CGColor;
        self.rechargeBut.userInteractionEnabled = NO;
        [self.rechargeBut setTitle:@"今日已兑换" forState:UIControlStateNormal];
        [self.rechargeBut setTitleColor:HEXCOLOR(0xCCCCCC) forState:UIControlStateNormal];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [UIView new];
    return v;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [UIView new];
    return view;
}
//开启计步
- (IBAction)kaiqi:(UIButton *)sender {
//    if([SYSTEMVERSION floatValue]>=8.0){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//    }
}
//兑换点击了
- (IBAction)rechargeClick:(UIButton *)sender {
    NSInteger num = [self.chepiaoCount.text integerValue];

    if (num < 5000) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            MTOkTishiView *okView = [[MTOkTishiView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
            okView.content.text = @"兑换失败\n今日尚未积满5000步";
            okView.bgView.backgroundColor = KMainPinkColor;
            okView.goButClick = ^(NSString *  s) {
            };
            [[UIApplication sharedApplication].keyWindow addSubview:okView];
        });
    }else {
        if ([[NSString stringWithFormat:@"%@",KUSER.isReceive]isEqualToString:@"1"]) {
            [self.view maketishiToast:@"今日已兑换"];
           
        }else {
            [self duihuan];
        }
    }
    
}
- (void)duihuan{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            [[UIApplication sharedApplication].keyWindow maketicket2Toast:@"20"];
            self.rechargeBut.layer.borderWidth = 2;
            self.rechargeBut.layer.borderColor = HEXCOLOR(0xCCCCCC).CGColor;
            self.rechargeBut.userInteractionEnabled = NO;
            [self.rechargeBut setTitle:@"今日已兑换" forState:UIControlStateNormal];
            [self.rechargeBut setTitleColor:HEXCOLOR(0xCCCCCC) forState:UIControlStateNormal];
            
            [self getUserInfo];
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc userSign];
}

- (void)getBushu{
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        if (code == 1) {

        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findStep:self.chepiaoCount.text];
}


- (void)reloadData{
    if ([CMPedometer isStepCountingAvailable]) {// start  end
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDate *now = [NSDate date];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
        NSDate *startDate = [calendar dateFromComponents:components];
        NSLog(@"++++++++++++++++ :%@",startDate);
        [_pedometer startPedometerUpdatesFromDate:startDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
            if (error)
            {
                NSLog(@"error===%@",error);
                dispatch_async(dispatch_get_main_queue(), ^{
//                    self.lab.text = @"无法记录步数，去授权>>";
                    self.kaiqiBut.layer.borderWidth = 2;
                    self.kaiqiBut.layer.borderColor = KMainBlueColor.CGColor;
                    self.kaiqiBut.userInteractionEnabled = YES;
                    [self.kaiqiBut setTitleColor:KMainBlueColor forState:UIControlStateNormal];
                    [self.kaiqiBut setTitle:@"开启记步" forState:UIControlStateNormal];
                });
            }
            else {
               
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.kaiqiBut.layer.borderWidth = 2;
                    self.kaiqiBut.layer.borderColor = HEXCOLOR(0xCCCCCC).CGColor;
                    self.kaiqiBut.userInteractionEnabled = NO;
                    [self.kaiqiBut setTitle:@"已开启" forState:UIControlStateNormal];
                    [self.kaiqiBut setTitleColor:HEXCOLOR(0xCCCCCC) forState:UIControlStateNormal];
                    NSInteger numberOfSteps = [pedometerData.numberOfSteps integerValue];
                    self.chepiaoCount.text = [NSString stringWithFormat:@"%ld",(long)numberOfSteps];
                    [self getBushu];
                });
                
            }
        }];
    }else{
        NSLog(@"不可用===");
        dispatch_async(dispatch_get_main_queue(), ^{
            self.kaiqiBut.layer.borderWidth = 2;
            self.kaiqiBut.layer.borderColor = KMainBlueColor.CGColor;
            self.kaiqiBut.userInteractionEnabled = YES;
            [self.kaiqiBut setTitleColor:KMainBlueColor forState:UIControlStateNormal];
            [self.kaiqiBut setTitle:@"开启记步" forState:UIControlStateNormal];
        });
    }
}




- (void)getUserInfo{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            KUSER = data;
            NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
            NSDictionary *dic = [KUSER mj_keyValues];
            //             操作者将包含用户信息的数组arr持久化
            [userInfo setValue:dic forKey:@"userinfo"];
            //把值立即存进去,放置数据丢失
            [[NSUserDefaults standardUserDefaults]synchronize];
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findUserInfo];
}



- (void)shareClick {
    //显示分享面板
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        [self shareImageAndTextToPlatformType:platformType];
    }];
}
- (void)shareImageAndTextToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享标识
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //设置文本
    messageObject.text = @"";
    
    MTYaoQingView *yao = [[MTYaoQingView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];
    yao.codeView.image = [self createCode];
    
    UIImage *img = [self makeImageWithView:yao withSize:CGSizeMake(375, 667)];
    //    [self getImage:yao];
    //创建图片内容对象
    //    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.schoolName descr:desc thumImage:[UIImage imageNamed:@"icon_logo"]];
    //
    //    NSString *str = [NSString stringWithFormat:@"%@",self.jumpUrl];
    //    shareObject.webpageUrl = str;
    //    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"加入我们" descr:@"" thumImage:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559036016108&di=eef30c1102e4f524d000736bfafe19c8&imgtype=0&src=http%3A%2F%2Fac-r.static.booking.cn%2Fimages%2Fhotel%2Fmax1024x768%2F987%2F98767654.jpg"];
    //    NSString *str = [NSString stringWithFormat:@"%@",self.jumpUrl];
    //    shareObject.webpageUrl = @"www.baidu.com";
    
    //创建图片内容对象
    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
    //如果有缩略图，则设置缩略图
    shareObject.thumbImage = [UIImage imageNamed:@"AppIcon"];
    [shareObject setShareImage:img];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}

- (UIImage *)createCode{
    //
    NSArray *filters = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];
    NSLog(@"%@",filters);
    //二维码过滤器
    CIFilter *qrImageFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //设置过滤器默认属性
    [qrImageFilter setDefaults];
    //将字符串转换成 NSdata (虽然二维码本质上是 字符串,但是这里需要转换,不转换就崩溃)
    // 字符串可以随意换成网址等
    NSString *url = self.jumpUrl;
    
    NSData *qrImageData = [url dataUsingEncoding:NSUTF8StringEncoding];
    //我们可以打印,看过滤器的 输入属性.这样我们才知道给谁赋值
    NSLog(@"%@",qrImageFilter.inputKeys);
    //设置过滤器的 输入值 ,KVC赋值
    [qrImageFilter setValue:qrImageData forKey:@"inputMessage"];
    //取出图片
    CIImage *qrImage = [qrImageFilter outputImage];
    //但是图片 发现有的小 (27,27),我们需要放大..我们进去CIImage 内部看属性
    qrImage = [qrImage imageByApplyingTransform:CGAffineTransformMakeScale(20, 20)];
    //转成 UI的 类型
    UIImage *qrUIImage = [UIImage imageWithCIImage:qrImage];
    //----------------给 二维码 中间增加一个 自定义图片----------------
    //开启绘图,获取图形上下文 (上下文的大小,就是二维码的大小)
    UIGraphicsBeginImageContext(qrUIImage.size);
    //把二维码图片画上去. (这里是以,图形上下文,左上角为 (0,0)点)
    [qrUIImage drawInRect:CGRectMake(0, 0, qrUIImage.size.width, qrUIImage.size.height)];
    //再把小图片画上去
    UIImage *sImage = [UIImage imageNamed:@"icon108"];
    CGFloat sImageW = 100;
    CGFloat sImageH= sImageW;
    CGFloat sImageX = (qrUIImage.size.width - sImageW) * 0.5;
    CGFloat sImgaeY = (qrUIImage.size.height - sImageH) * 0.5;
    [sImage drawInRect:CGRectMake(sImageX, sImgaeY, sImageW, sImageH)];
    //获取当前画得的这张图片
    UIImage *finalyImage = UIGraphicsGetImageFromCurrentImageContext();
    //关闭图形上下文
    UIGraphicsEndImageContext();
    //设置图片
    return  finalyImage;
}

- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, YES, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}
@end
